﻿using System;
using System.Collections.Concurrent;
using System.Xml.Linq;

using iTool.Cloud.Center.Logger;

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace iTool.Cloud.Center.Logger
{

    public class iCenterLoggerProvider : ILoggerProvider
    {
        private readonly IDisposable? _onChangeToken;
        private iCenterLoggerConfiguration _currentConfig;
        private readonly ConcurrentDictionary<string, iCenterLogger> _loggers;

        public iCenterLoggerProvider(IOptionsMonitor<iCenterLoggerConfiguration> config)
        {
            _currentConfig = config.CurrentValue;
            _onChangeToken = config.OnChange(updatedConfig => _currentConfig = updatedConfig);
            _loggers = new ConcurrentDictionary<string, iCenterLogger>();
        }

        public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new iCenterLogger(name, GetCurrentConfig));

        private iCenterLoggerConfiguration GetCurrentConfig() => _currentConfig;

        public void Dispose()
        {
            _loggers.Clear();
            _onChangeToken?.Dispose();
        }
    }
}
